package com.bawei.module_home.ui.house

import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.BaseActivity
import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.base.state.Empty
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.Success
import com.bawei.lib_common.observeWithLifecycle
import com.bawei.lib_common.utils.ToastUtils
import com.bawei.module_home.R
import com.bawei.module_home.adapter.HouseManageAdapter
import com.bawei.module_home.databinding.ActivityHouseManageBinding
import com.bawei.module_home.http.HomeServiceViewModel
import dagger.hilt.android.AndroidEntryPoint

@Route(path = Router.HOUSE_MANAGE_PAGE)
@AndroidEntryPoint
class House_Manage_Activity : BaseActivity<BaseViewModel, ActivityHouseManageBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.activity_house_manage
    val mAdapter: HouseManageAdapter by lazy {
        HouseManageAdapter()
    }
    val mViewModel: HomeServiceViewModel by viewModels()
    override fun initView() {
        super.initView()
    }

    override fun initData() {

        mViewModel.getAllHouse()
        mBinding.houseManageRv.adapter = mAdapter
        mBinding.houseManageRv.layoutManager=LinearLayoutManager(this)
    }
    override fun initListener() {
        mBinding.editQuery.addTextChangedListener(object :TextWatcher{

            // 输入框内容改变
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            // 输入框内容改变
            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                querySearch(p0.toString())
            }

            override fun afterTextChanged(p0: Editable?) {
               querySearch(p0.toString())
            }

        })
        mBinding.btnBack.setOnClickListener {
            finish()
        }
    mViewModel.houseState.observeWithLifecycle(this){
        when( it){
            Empty -> {}
            is Failed ->{
                ToastUtils.showLong(this,it.message)
            }
            Loading ->{

            }
            Success -> {
                mAdapter.setData(mViewModel.houseList)
            }
        }
    }
    }

    private fun querySearch(text:String) {
        if (text.isNotEmpty()){
            mAdapter.setData(mViewModel.houseList.filter { it.enterpriseName.contains(text)})
        }else{
            mAdapter.setData(mViewModel.houseList)
        }

    }


}